package org.example.reentrantlock;

import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhengdp
 * @Description ReentrantLock 条件变量 使用测试
 * @Date 2022/11/5 22:56
 * @Created by zhengdp
 */
@Slf4j(topic = "c.ConditionTest")
public class ConditionTest {
    private static ReentrantLock LOCK = new ReentrantLock();
    public static void main(String[] args) {
        Condition condition1 = LOCK.newCondition();
        Condition condition2 = LOCK.newCondition();
        new Thread(() -> {
            LOCK.lock();
            log.info("获取到锁");
            try {
                log.info("进入 condition1");
                condition1.await();
                log.info("被唤醒，线程执行完毕");
            } catch (InterruptedException e) {
                // 在等待过程中 线程可以被打断
                throw new RuntimeException(e);
            }finally {
                LOCK.unlock();
            }

        },"t1").start();
        new Thread(() -> {
            LOCK.lock();
            log.info("获取到锁");
            try{
                log.info("进入到 condition2 中等待");
                condition2.await();
                log.info("唤醒 condition1");
                condition1.signal();
                log.info("被唤醒，线程执行完毕");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                LOCK.unlock();
            }
        },"t2").start();

        log.info("主线程沉睡两秒");
        Sleeper.sleep(2000);
        LOCK.lock();
        log.info("主线程唤醒 condition2");
        condition2.signal();
        LOCK.unlock();
    }
}
